package com.laicunba.event.listener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.event.PaySuccessEvent;
import com.laicunba.event.RateIncrCouponCreateEvent;
import com.laicunba.pojo.FinancingTargetBidDO;
import com.laicunba.pojo.FinancingTargetDO;
import com.laicunba.pojo.RateIncrCouponDO;
import com.laicunba.pojo.RateIncrCouponDefDO;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.FinancingTargetService;
import com.laicunba.service.RateIncrCouponDefService;
import com.laicunba.service.RegistryService;
import com.laicunba.service.UserService;
import com.laicunba.service.VcoinWalletService;

@Component
public class SlotMachinesListener implements ApplicationListener<PaySuccessEvent>, ApplicationEventPublisherAware {
	private static final Logger LOG = Logger.getLogger(SlotMachinesListener.class);

	private ApplicationEventPublisher applicationEventPublisher;
	@Autowired
	private RegistryService registryService;
	@Autowired
	private RateIncrCouponDefService rateIncrCouponDefService;
	@Autowired
	private FinancingTargetService financingTargetService;
	@Autowired
	private UserService userService;
	@Autowired
	private VcoinWalletService vcoinWalletService;

	@SuppressWarnings("unchecked")
	@Override
	public void onApplicationEvent(PaySuccessEvent event) {
		try {
			FinancingTargetBidDO bidDO = (FinancingTargetBidDO) event.getSource();
			RegistryDO onOffRegistry = registryService.get(RegistryDO.class, "act.slot-machines.open");
			DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(bidDO != null && bidDO.getType().equalsIgnoreCase("CPB") && onOffRegistry != null) {
				JSONArray actTimeArray = (JSONArray)new JSONParser().parse(onOffRegistry.getVal());
				if(actTimeArray != null) {
					Map<String, String> tempMap = (Map<String, String>) actTimeArray.get(0);
					if(tempMap != null && new Date().compareTo(sdf.parse(tempMap.get("start_time"))) >= 1 && new Date().compareTo(sdf.parse(tempMap.get("end_time"))) < 1) {
						FinancingTargetDO target = financingTargetService.get(FinancingTargetDO.class, bidDO.getFinancingTargetId());
						UserDO bidUser = userService.get(UserDO.class, bidDO.getBidUserId());
						UserDO inviter = userService.findInviteUser(bidDO.getBidUserId());
						//用户首次投资
						if(target != null && bidUser != null && inviter != null && userService.countBidTimesHasBankInfo(bidDO.getBidUserId()) == 1) {
							RateIncrCouponDefDO rateIncrDef = null;
							if(target.isNewInvestor()) {
								rateIncrDef = rateIncrCouponDefService.get(RateIncrCouponDefDO.class, "act-slot-machines-rate-incr-1");
								vcoinWalletService.add(inviter.getId(), 35, "SLOT_MACHINES", "运营活动-老虎机");
							} else {
								rateIncrDef = rateIncrCouponDefService.get(RateIncrCouponDefDO.class, "act-slot-machines-rate-incr-2");
								vcoinWalletService.add(inviter.getId(), 50, "SLOT_MACHINES", "运营活动-老虎机");
							}
							if (rateIncrDef == null) {
								LOG.error(String.format("【老虎机活动】发放加息券出错，加息券未定义，rateIncrDef为[%s]", rateIncrDef));
							} else if(rateIncrDef.getUsedQuantity() >= rateIncrDef.getTotalQuantity() || (rateIncrDef.getEndTime() != null && new Date().after(rateIncrDef.getEndTime()))) {
								LOG.error(String.format("【老虎机活动】发放加息券出错，加息券已发完或加息券信息已过期，已发放[%s]张，发行量为[%s]，加息券定义结束时间为[$s]，当前时间为[%s]", rateIncrDef.getUsedQuantity(), rateIncrDef.getTotalQuantity(), rateIncrDef.getEndTime(), new Date()));
							} else {
								RateIncrCouponDO rateIncrCouponDO = rateIncrCouponDefService.send2User(rateIncrDef.getId(), inviter.getId(), false, "slot_" + bidUser.getMobile());
								RateIncrCouponCreateEvent rateIncrEvent = new RateIncrCouponCreateEvent(rateIncrCouponDO);
								applicationEventPublisher.publishEvent(rateIncrEvent);
							}
						}
					}
				}
			}
			
		} catch (Exception e) {
			LOG.error("【老虎机活动】加息券发放出错了", e);
		}
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.applicationEventPublisher = applicationEventPublisher;
	}
	
}
